﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CefSharp.OffScreen;
using CefSharp;
using System.Data;

namespace Chen.CefWebKit
{
    class UserCookie
    {
        SqliteHelper sqlite;
        public UserCookie(SqliteHelper sqlitex)
        {
            sqlite = sqlitex;
        }
        public System.Net.CookieContainer cookie
        {
            get
            {
                CookieContainer _cookie = new System.Net.CookieContainer();
                DataTable dt = new DataTable();
                dt = sqlite.select("SELECT datetime((expires_utc/1000000)-11644473600, 'unixepoch', 'localtime')as expires_utc ,host_key,httponly,name,path,secure,value FROM cookies");
                foreach (DataRow dr in dt.Rows)
                {
                    try
                    {
                        System.Net.Cookie ck = new System.Net.Cookie();
                        ck.Domain = dr["host_key"].ToString();
                        ck.Expires = ToDateTime(dr["expires_utc"]);
                        ck.HttpOnly = Convert.ToBoolean(dr["httponly"]);
                        ck.Name = dr["name"].ToString();
                        ck.Path = dr["path"].ToString();
                        ck.Secure = Convert.ToBoolean(dr["secure"]);
                        ck.Value = System.Web.HttpUtility.UrlEncode(dr["value"].ToString());
                        _cookie.Add(ck);
                    }
                    catch
                    {

                    }
                }
                return _cookie;
            }
            set
            {
                foreach (System.Net.Cookie ck in GetAllCookies(value))
                {

                    DataTable chkck = sqlite.select("SELECT * FROM cookies where host_key='" + ck.Domain + "' and name='" + ck.Name + "'");
                    if (chkck.Rows.Count > 0)
                    {
                        string sqlstr = "UPDATE cookies SET value = @value WHERE host_key=@host_key and name=@name";
                        Dictionary<string, string> strdic = new Dictionary<string, string>();
                        strdic.Add("value", ck.Value);
                        strdic.Add("host_key", ck.Domain);
                        strdic.Add("name", ck.Name);
                        sqlite.paramadd(sqlstr, strdic);
                    }
                    else
                    {
                        string sqlstr = "INSERT INTO cookies(creation_utc,host_key,name,value,path,expires_utc,secure,httponly,last_access_utc,has_expires,persistent,priority,firstpartyonly)" +
                            " VALUES (@creation_utc,@host_key,@name,@value,@path,@expires_utc,@secure,@httponly,@last_access_utc,1,1,1,0)";
                        Dictionary<string, string> strdic = new Dictionary<string, string>();
                        strdic.Add("creation_utc", "13092983614422683");
                        strdic.Add("host_key", ck.Domain);
                        strdic.Add("name", ck.Name);
                        strdic.Add("value", ck.Value);
                        strdic.Add("path", ck.Path);
                        strdic.Add("expires_utc", "14092983614422683");
                        strdic.Add("secure", Convert.ToInt32(ck.Secure).ToString());
                        strdic.Add("httponly", Convert.ToInt32(ck.HttpOnly).ToString());
                        strdic.Add("last_access_utc", "13092983614422683");
                        sqlite.paramadd(sqlstr, strdic);
                    }
                }
            }
        }
        public void ClearAllCookie()
        {
            sqlite.add("DELETE from cookies");
        }
        //private double ConvertDateTimeInt(System.DateTime time)
        //{
        //    double intResult = 0;
        //    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        //    intResult = (time - startTime).TotalSeconds;
        //    return intResult;
        //}
        //private DateTime ConvertIntDatetime(long utc)
        //{
        //    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1,0,0,0));
        //    Double time = (Convert.ToDouble(utc) / 1000000.0) - 11644473600F;
        //    startTime = startTime.AddSeconds(time);
        //    startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 )
        //    return startTime;
        //}
        private System.Net.Cookie[] GetAllCookies(CookieContainer cookie)
        {
            CookieContainer cc = cookie;
            List<System.Net.Cookie> lstCookies = new List<System.Net.Cookie>();

            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (System.Net.Cookie c in colCookies) lstCookies.Add(c);
            }
            return lstCookies.ToArray();
        }
        private DateTime ToDateTime(object value)
        {
            try
            {
                return Convert.ToDateTime(value);
            }
            catch
            {
                return new DateTime();
            }
        }
    }
}
